package model

import (
	"blog2021/tools/logger"
	"fmt"
	"sort"
)

type ArchiveItem struct {
	YearMonth string
	Posts     []Post
}

type Archive struct {
	Title      string
	SubTitle   string
	OrderTitle string
	OrderUrl   string
	Items      []ArchiveItem
}

func GetArchive(order string) Archive {
	var archive Archive
	archive.Title = "归档"
	var posts []Post
	err := db.Select(PostLessFields).Order("created_at " + order).Find(&posts).Error
	if err != nil {
		logger.Error(err)
		return archive
	}

	visits := 0
	var mp = make(map[string][]Post)
	for _, post := range posts {
		yearMonth := post.CreatedAt.Format("2006年01月")
		mp[yearMonth] = append(mp[yearMonth], post)
		visits += post.Pv
	}
	for k, v := range mp {
		var item ArchiveItem
		item.YearMonth = k
		item.Posts = v
		archive.Items = append(archive.Items, item)
	}
	sort.Slice(archive.Items, func(i, j int) bool {
		if order == "desc" {
			return archive.Items[i].YearMonth > archive.Items[j].YearMonth
		}
		return archive.Items[i].YearMonth < archive.Items[j].YearMonth
	})

	if order == "desc" {
		archive.OrderUrl = "/archive/asc"
		archive.OrderTitle = "顺序展示"
	} else {
		archive.OrderUrl = "/archive/desc"
		archive.OrderTitle = "逆序展示"
	}

	archive.SubTitle = fmt.Sprintf("总月份数:%v 总文章数:%v 总访问量:%v", len(archive.Items), len(posts), visits)
	return archive
}
